#include "StdAfx.h"
#include "logichost.h"
#include "ExceedRdEvt.h"

CLogicHost::CLogicHost(utils::CPlugin& plugin):
CNTService( plugin.GetServiceName(), GetName(), plugin.GetDisplayName() ),
m_refPlugin(plugin)
{
    m_szPath = plugin.GetPath();
}

CLogicHost::~CLogicHost(void)
{
}

void CLogicHost::Run(DWORD /*argc*/, LPTSTR * /*argv*/)
{
    ReportStatus(SERVICE_START_PENDING);
    
    if(m_refPlugin.GetPath().empty() )
    {
        WriteEventLog(EVENTLOG_INFORMATION_TYPE, CATEGORY_SERVICE_EXECUTING_, EVMSG_SERVICEEMPTYSTARTED_, 0);
    }
    
    ReportStatus(SERVICE_START_PENDING);
    
    DWORD err = m_refPlugin.Start();

    if(ERROR_SUCCESS != err)
    {
        ReportStatus(SERVICE_START_PENDING);
        std::wstringstream str;
        str << L"0x" << std::hex << std::setfill(L'0') << std::setw(8) << err;
        WriteEventLog(EVENTLOG_ERROR_TYPE, CATEGORY_SERVICE_EXECUTING_, EVMSG_LOAD_PLUGIN_START_, 2, str.str().c_str(), m_refPlugin.GetPath().c_str() );
        return;
    }
    
    ReportStatus(SERVICE_RUNNING);
    
    WriteEventLog(EVENTLOG_SUCCESS, CATEGORY_SERVICE_EXECUTING_, EVMSG_SERVICESTARTED_, 1, m_refPlugin.GetDisplayName() );
    
    m_refPlugin.Run();

    m_StopEvent.Wait();
}

void CLogicHost::Stop()
{
    m_refPlugin.Stop();
    
    ReportStatus(SERVICE_STOP_PENDING);
    
    WriteEventLog(EVENTLOG_SUCCESS, CATEGORY_SERVICE_EXECUTING_, EVMSG_SERVICESTOPPED_,1, m_refPlugin.GetDisplayName() );
    
    m_StopEvent.Set();
    
    ReportStatus(SERVICE_STOP_PENDING);
}

void CLogicHost::Shutdown()
{
    m_refPlugin.ServiceControlHandler(SERVICE_CONTROL_SHUTDOWN);
    CNTService::Shutdown();
}

void CLogicHost::Pause()
{
    m_refPlugin.ServiceControlHandler(SERVICE_CONTROL_PAUSE);
    CNTService::Pause();
}

void CLogicHost::Continue()
{
    m_refPlugin.ServiceControlHandler(SERVICE_CONTROL_CONTINUE);
    CNTService::Continue();
}

void CLogicHost::DefaultCtrlHandler(DWORD dwCtrlCode)
{
    m_refPlugin.ServiceControlHandler(dwCtrlCode);
    CNTService::DefaultCtrlHandler(dwCtrlCode);
}

LPCWSTR CLogicHost::GetName()
{
    return L"LogicHost";
}

LPCWSTR CLogicHost::GetDisplayName()
{
    return L"LogicHost";
}

BOOL CLogicHost::PostInstallService()
{
    return ERROR_SUCCESS == m_refPlugin.RegService();
}

BOOL CLogicHost::PostRemoveService()
{
    return ERROR_SUCCESS == m_refPlugin.UnRegService();
}
